import QtQuick
import QtQuick.Controls
import Qool.Controls
import Qool

QoolControl {
    id: root

    property real defaultValue: 0
    property real value: defaultValue

    property Component barBackground: privateControl.defaultBarBackground
    property Component barIndicator: privateControl.defaultBarIndicator
    property Component barCover: privateControl.defaultBarCover

    property var textFromValue: function (x) {
        let v = (x * 100).toFixed(0)
        return v + '%'
    }

    property var valueFromText: function (x) {
        let v = x.replace('%', '').toInt()
        let r = v / 100
        return numGate.fix(r)
    }

    title: qsTr("滑块控件")

    contentItem: Item {
        id: mainItem
        Loader {
            id: barBgLoader
            anchors.fill: parent
            sourceComponent: root.barBackground
            z: -10
        }

        Loader {
            id: coverLoader
            width: indicator.x
            height: parent.height
            sourceComponent: root.barCover
            z: 5
        }

        Item {
            id: indicator
            DragHandler {
                acceptedButtons: Qt.LeftButton
                cursorShape: Qt.SizeHorCursor
                yAxis.enabled: false
                xAxis {
                    minimum: 0
                    maximum: mainItem.width - indicator.width
                }
            }
            Loader {
                id: indicatorLoader
                sourceComponent: root.barIndicator
                height: parent.height
            }
            width: indicatorLoader.width
            height: parent.height
            y: 0
            x: (parent.width - width) * root.value
            z: 10
            onXChanged: {
                root.value = x / (mainItem.width - indicator.width)
            }
        }
    }

    QoolNumberGate {
        id: numGate
    }

    QtObject {
        id: privateControl
        property Component defaultBarBackground: Rectangle {
            color: "black"
        }

        property Component defaultBarIndicator: Rectangle {
            Text {
                id: indiTT
                text: root.textFromValue(root.value)
                color: QoolStyle.textColor
                font.pixelSize: QoolStyle.controlMainTextFontPixelSize
                anchors.centerIn: parent
                padding: 3
            }
            color: QoolStyle.controlBackgroundColor
            implicitHeight: indiTT.implicitHeight
            implicitWidth: indiTT.font.pixelSize / 2 * 7
            z: -10
            border {
                width: 1
                color: QoolStyle.textColor
            }
        }

        property Component defaultBarCover: Rectangle {
            color: "steelblue"
            opacity: 0.75
        }
    }

    Behavior on value {
        enabled: root.animationEnabled
        NumberAnimation {
            duration: QoolStyle.controlMovementDuration
        }
    }
}
